package com.retail.bbq.cola.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.retail.bbq.cola.entity.ActivityUpcLevel;
import com.retail.bbq.cola.entity.StampCollectionExpirationNotice;
import com.retail.bbq.cola.entity.WechatCustomer;
import com.retail.bbq.cola.enums.ActivityUpcTypeEnum;
import com.retail.bbq.cola.enums.CommonEnum;
import com.retail.bbq.cola.enums.DeleteStatusEnum;
import com.retail.bbq.cola.enums.ErrorCodeEnum;
import com.retail.bbq.cola.exception.BusinessException;
import com.retail.bbq.cola.feign.ColaFeign;
import com.retail.bbq.cola.service.*;
import com.retail.bbq.cola.utils.Base64Util;
import com.retail.bbq.cola.utils.DateUtil;
import com.retail.bbq.cola.vo.request.ColaActivityPointRequest;
import com.retail.bbq.cola.vo.request.stampCollection.ActivityUpcLevelRequest;
import com.retail.bbq.cola.vo.request.stampCollection.ColaActivityPointQueryRequest;
import com.retail.bbq.cola.vo.request.stampCollection.ColaOrderListRequest;
import com.retail.bbq.cola.vo.request.stampCollection.LawsonStampCollectionRequest;
import com.retail.bbq.cola.vo.response.ColaActivityPointResponse;
import com.retail.bbq.cola.vo.response.stampCollection.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LawsonStampCollectionServiceImpl implements LawsonStampCollectionService {

    @Resource
    private WechatCustomerService wechatCustomerService;
    @Resource
    private ColaFeign colaFeign;
    @Resource
    private PlatformTenantClientService platformTenantClientService;
    @Resource
    private ActivityUpcLevelService activityUpcLevelService;
    @Resource
    private StampCollectionExpirationNoticeService stampCollectionExpirationNoticeService;
    @Resource
    private RedisTemplate<String, Integer> integerRedisTemplate;

    @Value("${api.client.campaignCode}")
    private String campaignCode;

    public static final String LS_CHANNEL = "LS";
    public static final Integer activityStampNum = 1;
    public static final Integer oneLotteryStampNum = 5;

    @Override
    public LawsonStampCollectionResponse queryOrder(LawsonStampCollectionRequest request) {
        if(StringUtils.isBlank(request.getMonth())){
            throw new BusinessException(500,"month不能为空");
        }
        LawsonStampCollectionResponse response = new LawsonStampCollectionResponse();
        response.setMonth(request.getMonth());
        if(StringUtils.isBlank(request.getOneid())){
            log.info("查询集章进度，oneid不能为空");
            return nullResponse(response);
        }
        //1.获取用户id
        WechatCustomer wechatCustomer = wechatCustomerService.getBaseMapper().selectOne(new LambdaQueryWrapper<WechatCustomer>()
                .eq(WechatCustomer::getOneid, request.getOneid())
                .eq(WechatCustomer::getIsDel, DeleteStatusEnum.no_del.getCode())
                .orderByDesc(WechatCustomer::getCreateTime)
                .last("limit 1"));
        if(Objects.isNull(wechatCustomer)){
            log.info("查询集章进度，无会员信息，返回为空");
            return nullResponse(response);
        }
        //2.请求可乐，调用订单查询接口
        List<ColaOrderListResponse.DataBean.ContentBean> colaOrderListResponse = colaQueryOrderList(request, wechatCustomer);
        if(CollectionUtils.isEmpty(colaOrderListResponse)){
            log.info("查询集章进度，订单结果为空");
            return nullResponse(response);
        }

        List<LawsonStampCollectionResponse.LawsonStampCollection> result = findStampCollectionInfo(request.getMonth(), colaOrderListResponse);
        int medalNum = result.stream().flatMap(collection -> collection.getGoodsList().stream())
                .filter(productInfo -> productInfo.getAwardMedalNum() != 0)
                .mapToInt(LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo::getAwardMedalNum)
                .sum();
        response.setMedalNum(medalNum);
        response.setLotteryNum(medalNum/oneLotteryStampNum);
        response.setTimeOutMedalNum(medalNum%oneLotteryStampNum);
        response.setOrderList(result);
        return response;
    }

    private LawsonStampCollectionResponse nullResponse(LawsonStampCollectionResponse response) {
        response.setMedalNum(0);
        response.setLotteryNum(0);
        response.setTimeOutMedalNum(0);
        response.setOrderList(Lists.newArrayList());
        return response;
    }

    @Override
    public LawsonStampCollectionTodoResponse orderMedalProcess(LawsonStampCollectionRequest request) {
        if(StringUtils.isBlank(request.getMonth())){
            String month = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
            request.setMonth(month);
        }
        log.info("orderMedalProcess request:{}", request);
        LawsonStampCollectionResponse lawsonStampCollectionResponse = this.queryOrder(request);
        int timeOutMedalNum = lawsonStampCollectionResponse.getTimeOutMedalNum();
        int totalStampNum = lawsonStampCollectionResponse.getMedalNum();
        List<LawsonStampCollectionResponse.LawsonStampCollection> orderList = lawsonStampCollectionResponse.getOrderList();
        LawsonStampCollectionTodoResponse response = new LawsonStampCollectionTodoResponse();
        response.setTotalStampNum(totalStampNum);
        response.setTodoList(findTodoList(orderList,timeOutMedalNum));
        return response;
    }

    private List<LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo> findTodoList(List<LawsonStampCollectionResponse.LawsonStampCollection> orderList, int timeOutMedalNum) {
        List<LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo> todoList = Lists.newArrayList();
        if(timeOutMedalNum == 0 || CollectionUtils.isEmpty(orderList)){
            return todoList;
        }
        for (LawsonStampCollectionResponse.LawsonStampCollection order : orderList) {
            for (LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo product : order.getGoodsList()) {
                // 根据 每个品的章数 展开对象
                for (int i = 0; i < product.getAwardMedalNum(); i++) {
                    if (todoList.size() >= timeOutMedalNum) {
                        return todoList; // 达到上限，直接返回
                    }
                    // 创建并添加 TodoInfo 对象
                    LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo todoInfo = new LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo();
                    todoInfo.setGoodsName(product.getGoodsName());
                    todoInfo.setGoodsType(product.getGoodsType());
                    todoInfo.setBrandIcon(product.getBrandIcon());
                    todoList.add(todoInfo);
                }
            }
        }
        return todoList;
    }

    @Override
    public LawsonStampCollectionExpirationReminder stampExpirationReminder(LawsonStampCollectionRequest request) {
        LawsonStampCollectionExpirationReminder reminder = new LawsonStampCollectionExpirationReminder();
//        //第一期9月开始提醒
//        LocalDateTime now = LocalDateTime.now();
//        LocalDateTime targetDate = LocalDateTime.of(2025, 9, 1, 0, 0);
//        if(now.isBefore(targetDate)){
//            //不需要提示，返回true
//            reminder.setIsExpirationNotice(true);
//            return reminder;
//        }
//        //获取当前时间上个月的时间
//        LocalDate lastMonth = LocalDate.now().minusMonths(1);
//        String lastMonthStr = lastMonth.format(DateTimeFormatter.ofPattern("yyMM"));
//        request.setMonth(lastMonthStr);
//        log.info("stampExpirationReminder request:{}", request);
//        reminder.setIsExpirationNotice(stampCollectionExpirationNoticeService.isExists(request));
//        if(!reminder.getIsExpirationNotice()){
//            //没提醒过
//            LawsonStampCollectionResponse lawsonStampCollectionResponse = this.queryOrder(request);
//            int totalStampNum = lawsonStampCollectionResponse.getMedalNum();
//            reminder.setIsExpirationNotice(true);
//            //上月剩余章数不为0，则提醒
//            if(lawsonStampCollectionResponse.getTimeOutMedalNum() != 0){
//                reminder.setIsExpirationNotice(false);
//                reminder.setMedalNum(totalStampNum);
//                reminder.setTimeOutMedalNum(lawsonStampCollectionResponse.getTimeOutMedalNum());
//                return reminder;
//            }
//        }
        return reminder;

    }

    @Override
    public LawsonStampCollectionExpirationReminder newStampExpirationReminder(LawsonStampCollectionRequest request) {
        LawsonStampCollectionExpirationReminder reminder = new LawsonStampCollectionExpirationReminder();
        //第一期9月开始提醒
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime targetDate = LocalDateTime.of(2025, 10, 1, 0, 0);
        if(now.isBefore(targetDate)){
            log.info("集章过期提醒，未到开始计算时间，返回为true");
            //不需要提示，返回true
            reminder.setIsExpirationNotice(true);
            return reminder;
        }
        if(StringUtils.isBlank(request.getMonth())){
            String month = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
            request.setMonth(month);
        }
        ColaActivityPointResponse.DataBean pointData = getPoint(request.getBuCode(), campaignCode, request.getOneid());
        if(Objects.isNull(pointData)){
            log.info("集章过期提醒，获取积分数据返回null，返回为true");
            reminder.setIsExpirationNotice(true);
            return reminder;
        }

        if(pointData.getTotalExpiredPoints() > 0){
            log.info("集章过期提醒，获取积分数据返回有过期积分，pointData:{}", JSON.toJSONString(pointData));
            Boolean hasNotice = stampCollectionExpirationNoticeService.isExists(request);
            reminder.setIsExpirationNotice(hasNotice);
            if(!hasNotice){
                BeanUtils.copyProperties(pointData, reminder);
            }
        }else{
            //没有过期积分
            reminder.setIsExpirationNotice(true);
        }
        return reminder;
    }

    public ColaActivityPointResponse.DataBean getPoint(String buCode, String campaignCode, String oneid){
        //1.获取用户id
        WechatCustomer wechatCustomer = wechatCustomerService.getBaseMapper().selectOne(new LambdaQueryWrapper<WechatCustomer>()
                .eq(WechatCustomer::getOneid, oneid)
                .eq(WechatCustomer::getIsDel, DeleteStatusEnum.no_del.getCode())
                .orderByDesc(WechatCustomer::getCreateTime)
                .last("limit 1"));
        if(Objects.isNull(wechatCustomer)){
            log.info("获取积分数据过程，非会员，返回为null");
            return null;
        }
        String accessToken = platformTenantClientService.getAccessToken();
        if(StringUtils.isBlank(accessToken)){
            log.info("获取积分数据过程，AccessToken获取失败");
            return null;
        }
        if(Objects.isNull(wechatCustomer.getThirdCustomerId())){
            log.error("获取积分数据过程,oneId:{} 未查询到绑定用户的customerId信息", wechatCustomer.getOneid());
            return null;
        }
        ColaActivityPointRequest colaActivityPointRequest = new ColaActivityPointRequest();
        colaActivityPointRequest.setCustomerId(wechatCustomer.getThirdCustomerId());
        colaActivityPointRequest.setCampaignCode(campaignCode);
        try{
            ColaActivityPointResponse colaActivityPointResponse = colaFeign.queryActivityPointByCustomerId(buCode, accessToken, colaActivityPointRequest);
            ColaActivityPointResponse.DataBean data = colaActivityPointResponse.getData();
            log.info("getPoint查询会员.customerId:{},积分:{}", wechatCustomer.getThirdCustomerId(), JSON.toJSONString(data));
            if(Objects.nonNull(data)){
                return data;
            }
            return null;
        }catch (Exception e){
            //如果接口异常，先不做通知
            log.error("oneId:"+oneid+"获取积分数据过程,发送异常", e);
            return null;
        }
    }


    @Override
    public LawsonStampCollectionTodoResponse newOrderMedalProcess(LawsonStampCollectionRequest request) {
        LawsonStampCollectionTodoResponse response = new LawsonStampCollectionTodoResponse();
        ColaActivityPointResponse.DataBean pointData = getPoint(request.getBuCode(), campaignCode, request.getOneid());
        if(Objects.isNull(pointData)){
            log.info("todo进度查询 -> 查询积分为空");
            response.setTotalStampNum(0);
            response.setTodoList(Lists.newArrayList());
            return response;
        }

        if(pointData.getTotalValidPoints() == 0){
            log.info("todo进度查询 -> 有效积分为：{},等于零,积分todo列表为空", pointData.getTotalValidPoints());
            response.setTotalStampNum(pointData.getTotalValidPoints() % oneLotteryStampNum);
            response.setTodoList(Lists.newArrayList());
            return response;
        }

        response.setTotalStampNum(pointData.getTotalValidPoints());
        //余数为0代表当前列表满了
        int pointRemainder = pointData.getTotalValidPoints() % oneLotteryStampNum;
        int queryListSize = pointRemainder == 0 ? oneLotteryStampNum : pointRemainder;
        response.setTodoList(newFindTodoList(queryListSize, request, Boolean.TRUE));
        return response;
    }

    private List<LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo> newFindTodoList(int num, LawsonStampCollectionRequest request, Boolean needaAllPoints) {
        List<LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo> todoList = new ArrayList<>();
        List<ColaActivityPointQueryResponse.DataBean> toDoDate = getToDoDate(request, needaAllPoints);
        if(CollectionUtils.isEmpty(toDoDate)){
            return todoList;
        }
        for(ColaActivityPointQueryResponse.DataBean dataBean : toDoDate){
            String remark = dataBean.getRemark();
            ActivityUpcLevel info = activityUpcLevelService.getActivityUpcInfo(remark);
            for (int i = 0; i < dataBean.getPoints(); i++) {
                if (todoList.size() >= num) {
                    return todoList; // 达到上限，直接返回
                }
                // 创建并添加 TodoInfo 对象
                LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo todoInfo = new LawsonStampCollectionTodoResponse.LawsonStampCollectionTodoInfo();
                todoInfo.setGoodsName(remark);
                todoInfo.setGoodsType(info.getType());
                todoInfo.setBrandIcon(info.getBrandIcon());
                todoList.add(todoInfo);
                //不判断是否是明细产品，这个由ocr判断返回双倍积分
//                if(ActivityUpcTypeEnum.STAR_GOODS.getCode() == info.getType() && todoList.size() < num){
//                    i++;
//                    todoList.add(todoInfo);
//                }
            }
        }
        return todoList;
    }

    private List<ColaActivityPointQueryResponse.DataBean> getToDoDate(LawsonStampCollectionRequest request, Boolean needaAllPoints) {
        //1.查询积分列表数据
        WechatCustomer userInfo = wechatCustomerService.getUserInfo(request.getOneid());
        if(Objects.isNull(userInfo.getThirdCustomerId())){
            log.error("查询todo进度,oneId:{} 未查询到绑定用户的customerId信息", userInfo.getOneid());
            return null;
        }
        ColaActivityPointQueryRequest pointQueryRequest = new ColaActivityPointQueryRequest();
        pointQueryRequest.setSort("createTime%2Cdesc");
        ZoneOffset offset = ZoneOffset.ofHours(8);
        LocalDateTime firstDayOfMonth = LocalDate.now()
                .withDayOfMonth(1)
                .atStartOfDay();
        OffsetDateTime firstDayWithOffset = firstDayOfMonth.atOffset(offset);
        OffsetDateTime currentTime = OffsetDateTime.now(offset);
        DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
        String firstDayStr = firstDayWithOffset.format(formatter);
        String currentTimeStr = currentTime.format(formatter);
        pointQueryRequest.setExpression(Base64Util.encode("leftPoints gt 0"
                + " AND channelCode eq LS"
                + " AND changeType eq increase"
                + " AND customerId eq "+ userInfo.getThirdCustomerId())
        );
        String accessToken = platformTenantClientService.getAccessToken();
        try{
            log.info("开始调用可乐查询积分列表接口，请求参数：{}", JSON.toJSONString(pointQueryRequest));
            ColaActivityPointQueryResponse queryResponse = colaFeign.queryActivityPointList(request.getBuCode(), campaignCode, accessToken, pointQueryRequest.getSort(), pointQueryRequest.getExpression());
            //2.获取num个商品信息
            log.info("开始调用可乐查询积分列表接口，请求参数：{}，应答：{}", JSON.toJSONString(pointQueryRequest), JSON.toJSONString(queryResponse));
            if(Objects.isNull(queryResponse) || CollectionUtils.isEmpty(queryResponse.getData())){
                return null;
            }
            return queryResponse.getData();
        }catch (Exception e){
            log.error("查询用户积分列表异常", e);
            return null;
        }
    }

    private List<LawsonStampCollectionResponse.LawsonStampCollection> findStampCollectionInfo(String month,
                                         List<ColaOrderListResponse.DataBean.ContentBean> colaOrderListResponse) {
        List<LawsonStampCollectionResponse.LawsonStampCollection> result = Lists.newArrayList();
        for(ColaOrderListResponse.DataBean.ContentBean order : colaOrderListResponse){
            Integer point = order.getPoint();
            LawsonStampCollectionResponse.LawsonStampCollection stampCollection = new LawsonStampCollectionResponse.LawsonStampCollection();
            stampCollection.setPoint(point);
            stampCollection.setOrderTime(DateUtil.dateToStrWithTimeZone(order.getCreateTime()));
            List<LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo> priceInfo = Lists.newArrayList();
            List<ColaOrderListResponse.DataBean.ContentBean.OrderDetail.ProductInfos> productInfos = order.getOrderDetail().getProductInfos();
            if(CollectionUtils.isEmpty(productInfos)){
                stampCollection.setGoodsList(priceInfo);
                result.add(stampCollection);
                continue;
            }
            for(ColaOrderListResponse.DataBean.ContentBean.OrderDetail.ProductInfos product : productInfos){
                LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo info = new LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo();
                info.setGoodsName(product.getTitle());
                ActivityUpcLevel activity = activityUpcLevelService.getActivityUpcInfoByMonth(product.getTitle(), month);
                info.setBrandIcon(activity.getBrandIcon());
                info.setGoodsType(activity.getType());
                int skuCnt = product.getSkuCnt();
                info.setGoodsNum(skuCnt);
                int awardMedalNum = ActivityUpcTypeEnum.STAR_GOODS.getCode() == activity.getType()
                        ? 2 * activityStampNum * skuCnt : activityStampNum * skuCnt;
                info.setAwardMedalNum(awardMedalNum);
                priceInfo.add(info);
            }
            processList(priceInfo,point);
            stampCollection.setGoodsList(priceInfo);
            result.add(stampCollection);
        }
        //按时间排序
        result.sort(Comparator.comparing(LawsonStampCollectionResponse.LawsonStampCollection::getOrderTime).reversed());
        return result;
    }

    public void processList(List<LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo> a, int point) {
        int sum = 0;
        int lastNonZeroIndex = -1; // 记录最后一个非零元素的索引
        for (int i = 0; i < a.size(); i++) {
            LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo current = a.get(i);
            if (sum >= point) {
                // 当前和已满足，后续元素置零
                current.setAwardMedalNum(0);
            } else {
                sum += current.getAwardMedalNum();
                lastNonZeroIndex = i;
            }
        }

        // 处理累加和不足或超过的情况
        if (sum != point) {
            if (lastNonZeroIndex >= 0) {
                LawsonStampCollectionResponse.LawsonStampCollection.ProductInfo last = a.get(lastNonZeroIndex);
                int diff = point - (sum - last.getAwardMedalNum());
                last.setAwardMedalNum(diff);
                // 超过 point 时，后续元素置零
                if (sum > point) {
                    for (int i = lastNonZeroIndex + 1; i < a.size(); i++) {
                        a.get(i).setAwardMedalNum(0);
                    }
                }
            }
        }
    }

    private List<ColaOrderListResponse.DataBean.ContentBean> colaQueryOrderList(LawsonStampCollectionRequest request, WechatCustomer wechatCustomer) {
        String accessToken = platformTenantClientService.getAccessToken();
        if(StringUtils.isBlank(accessToken)){
            throw new BusinessException(ErrorCodeEnum.GET_ACCESS_TOKEN_FAIL);
        }
        log.info("查询可乐订单开始,oneId:{}", wechatCustomer.getOneid());
        ColaOrderListRequest colaOrderListRequest = new ColaOrderListRequest();
        List<ColaOrderListResponse.DataBean.ContentBean> content = Lists.newArrayList();
        if(Objects.isNull(wechatCustomer.getThirdCustomerId())){
            log.error("查询可乐订单开始,oneId:{} 未查询到绑定用户的customerId信息", wechatCustomer.getOneid());
            return content;
        }
        int page = 0;
        int size = 100;
        // 1. 解析 yyyymm 为 YearMonth 对象
        YearMonth yearMonth = YearMonth.parse(request.getMonth(), DateTimeFormatter.ofPattern("yyyyMM"));
        LocalDate firstDayOfMonth = yearMonth.atDay(1);  // 月初
        LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();        // 月末
        // 3. 转换为带时区的 ZonedDateTime（默认系统时区）
        ZoneId zone = ZoneId.of("Asia/Shanghai");
        ZonedDateTime startOfMonth = firstDayOfMonth.atStartOfDay(zone);
        ZonedDateTime endOfMonth = lastDayOfMonth.atTime(23, 59, 59).atZone(zone);
        DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
        // 4. 格式化为 ISO 8601
        String firstDayStr = startOfMonth.format(formatter);
        String endTimeStr = endOfMonth.format(formatter);
        while (true) {
            colaOrderListRequest.setPage(page);
            colaOrderListRequest.setSize(size);
            colaOrderListRequest.setSort("createTime%2Cdesc");
            colaOrderListRequest.setExpression(Base64Util.encode("customerId eq "+ wechatCustomer.getThirdCustomerId()
                    + " AND campaignCode eq " + campaignCode
                    + " AND channel eq LS"
                    + " AND createTime ge " + firstDayStr
                    + " AND createTime le " + endTimeStr)
            );
            log.info("查询可乐订单,oneId:{},current page:{},request:{}", wechatCustomer.getOneid(), page, JSONObject.toJSONString(colaOrderListRequest));
            ColaOrderListResponse colaOrderListResponse = colaFeign.queryOrderList(request.getBuCode(), campaignCode, accessToken, colaOrderListRequest.getSort(), colaOrderListRequest.getExpression());
            if(Objects.isNull(colaOrderListResponse) || !colaOrderListResponse.getSuccess() || Objects.isNull(colaOrderListResponse.getData())){
                log.error("查询可乐订单失败,page:{},size:{},request:{},response:{}", page, size,
                        JSON.toJSONString(request), JSON.toJSONString(colaOrderListResponse));
                throw new BusinessException(ErrorCodeEnum.COLA_QUERY_ORDER_FAIL);
            }
            ColaOrderListResponse.DataBean data = colaOrderListResponse.getData();
            content.addAll(colaOrderListResponse.getData().getContent());
            log.info("查询可乐订单成功,oneId:{},page:{},订单数:{}", wechatCustomer.getOneid(), page, content.size());
            log.info("查询可乐订单成功,oneId:{},page:{},订单详情:{}", wechatCustomer.getOneid(), page, JSON.toJSONString(content));
            page++;
            if(data.getContent().size() < size || data.getTotalPages() <= page){
                break;
            }
        }
        return content;
    }
    
    /**
     * 查询用户积分波动情况
     * 1. 从Redis缓存中获取用户上次的总积分值（旧积分）
     * 2. 调用实时接口获取用户最新的总积分值（新积分）
     * 3. 将最新的总积分值缓存到Redis中，供下次查询使用
     * 4. 返回新旧积分值，供前端实现增量积分动效展示
     * 
     * @param request 包含buCode、oneid等信息的请求参数
     * @return LawsonStampPointFluctuationResponse 包含旧总积分和新总积分的响应对象
     */
    @Override
    public LawsonStampPointFluctuationResponse stampPointFluctuation(LawsonStampCollectionRequest request) {
        LawsonStampPointFluctuationResponse response = new LawsonStampPointFluctuationResponse();
        
        // 构造Redis缓存key
        String redisKey = "stamp_point:" + request.getOneid();
        
        // 从Redis获取旧的总积分
        Integer oldTotalPoints = integerRedisTemplate.opsForValue().get(redisKey);
        response.setOldTotalPoints(oldTotalPoints);
        
        // 调用实时接口获取最新的积分数据
        ColaActivityPointResponse.DataBean pointData = getPoint(request.getBuCode(), campaignCode, request.getOneid());
        if (Objects.nonNull(pointData)) {
            Integer newTotalPoints = pointData.getTotalPoints();
            response.setNewTotalPoints(newTotalPoints);
            
            // 将最新的总积分缓存到Redis中
            integerRedisTemplate.opsForValue().set(redisKey, newTotalPoints);
        }
        
        return response;
    }
}
